<template>
  <base-page-view class-name="approval-search">
    <view class="sticky-wrap search-block">
      <search-bar ref="search-bar" :keyword="listQuery.mobile" placeholder="手机号" text-align="left" background="#F5F5F5" :focus="true" @change="keyChange" @clear="keyClear" @search="search"></search-bar>
    </view>
    <view class="list">
      <view v-for="(gItem, gIndex) in list" :key="gIndex" class="item" @click="toDetail(gIndex)">
        <view class="item-header">
          <view class="item-name">{{ (gItem.created_at * 1000) | formatDate }}</view>
          <view class="item-state" :class="'item-state'+gItem.approval_status">{{ approvalObj[gItem.approval_status] }}</view>
        </view>
        <view class="item-content">
          <view v-for="(item,index) in gItem.box_apply_goods_d_t_o_s" :key="index" class="line goods-line">
            <b-image class-name="item-pic" :src="item.image" mode="aspectFill" />
            <view class="item-detail">
              <view>
                <view>{{ item.goods_name }}</view>
                <view class="item-stock">当前我的云仓库存：{{ item.stock_number }}</view>
              </view>
              <view class="between-wrapper">
                <view class="item-price">{{ item.goods_price | formatMoney }}</view>
                <view class="item-number">{{ item.goods_number }}</view>
              </view>
            </view>
          </view>
          <view class="line">
            <view class="label">申购单号</view>
            <view class="value">{{ gItem.apply_no }}</view>
          </view>
          <view class="line">
            <view class="label">申购人昵称</view>
            <view class="value">{{ gItem.apply_nickname }}</view>
          </view>
          <view class="line">
            <view class="label">申购人电话</view>
            <view class="value phone-value" @click.stop="$callPhone(gItem.apply_mobile)">
              <view>{{ gItem.apply_mobile }}</view>
              <b-image class-name="icon" src="/static/images/box/icon_phone.png" mode="aspectFit" :is-asset="true" />
            </view>
          </view>
          <view class="footer-line">
            <view class="money">{{ gItem.goods_total_amt | formatMoney }}</view>
            <view v-if="gItem.approval_status === 1" class="btn-line">
              <view class="btn" @click.stop="btnClick(3, gIndex)">驳回</view>
              <view v-if="gItem.stock_number_to_add > 0" class="btn main" @click.stop="btnClick(1, gIndex)">
                <view>补库存(差{{ gItem.stock_number_to_add }}箱)</view>
              </view>
              <view v-else class="btn main" @click.stop="btnClick(2, gIndex)">通过</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <base-list-state :list-length="listLength" :min-length="3" :list-query="{page_no: listQuery.page_no, page_size: listQuery.page_size}" :list-state="listState" :list-empty="listEmpty" />
    <confirm-popup ref="confirm">
      <template slot="content">
        <view v-if="handleObj.approvalStatus===3" class="reject-block">
          <view class="title">选择理由</view>
          <view class="content">
            <view class="type-item" @click="handleObj.rejectType = 1;handleObj.rejectReason='';handleObj.leastNum = 10">
              <image v-if="handleObj.rejectType === 1" src="/static/images/icon/icon_radio_active.png" mode="aspectFit" />
              <image v-else src="/static/images/icon/icon_radio.png" mode="aspectFit" />
              <view>未收到货款</view>
            </view>
            <view class="type-item" @click="handleObj.rejectType = 2">
              <image v-if="handleObj.rejectType === 2" src="/static/images/icon/icon_radio_active.png" mode="aspectFit" />
              <image v-else src="/static/images/icon/icon_radio.png" mode="aspectFit" />
              <view>其他</view>
            </view>
            <view class="input-item">
              <input v-model="handleObj.rejectReason" type="text" placeholder="请输入驳回理由" maxlength="10" :disabled="handleObj.rejectType === 1" @input="inputChange" />
              <view class="number">{{ handleObj.leastNum }}</view>
            </view>
          </view>
        </view>
        <view v-else-if="handleObj.approvalStatus===2" class="pass-warn-block">
          <view>为保障您的权益~</view>
          <view class="warn">请确认您<text>已线下收到了货款</text></view>
          <view>确认后云仓库存将扣减，划拨至申购人的云仓中。~</view>
          <view class="bg">*未收到货款前，请不要点击确认！</view>
        </view>
      </template>
    </confirm-popup>
  </base-page-view>
</template>
<script>
import searchBar from '@/components/searchBar/index'
import confirmPopup from '@/components/confirmPopup/index'
import { debounce, formatUrlParam } from '@/utils/tools'
import './search.scss'
export default {
  name: 'ApprovalSearch',
  components: {
    searchBar,
    confirmPopup
  },
  data() {
    return {
      createOrderPermission: false,
      approvalObj: {
        '1': '待审批',
        '2': '已通过',
        '3': '已驳回',
        '4': '已撤销'
      },
      listQuery: {
        approval_status: '',
        mobile: '',
        page_no: 1,
        page_size: 10
      },
      curent_page_no: 1, // 用来操作某条记录后更新数据
      list: [],
      listState: {
        loading: true,
        more: true
      },
      listEmpty: { type: 'empty_search', text: '没有搜索到相关的审批单' },
      handleObj: {
        id: '',
        approvalStatus: '', // 审批状态：2-审批通过，3-审批驳回
        rejectType: 1,
        rejectReason: '',
        leastNum: 10
      }
    }
  },
  computed: {
    listLength: function() {
      return this.list.length
    }
  },
  onLoad() {
    this.createOrderPermission = this.userInfo && this.userInfo.boxPermission && this.userInfo.boxPermission.includes(2)
  },
  onShow() {
    if (this.list && this.list.length) {
      this.updateList()
    }
  },
  onPullDownRefresh() {
    this.listQuery.page_no = 1
    this.fetchData(false)
  },
  onReachBottom: debounce(function() {
    if (this.listState.more && !this.listState.loading) {
      this.listQuery.page_no++
      this.fetchData()
    }
  }, 500),
  methods: {
    async fetchData(showLoading = true, query) {
      this.listState.loading = true
      const listQuery = query || this.listQuery
      const res = await this.$api.boxApi.getApproval({ ...listQuery }, showLoading)
      if (res.success) {
        if (listQuery.page_no === 1) {
          this.list = []
        }
        const list = (res.data || []).map(i => {
          const flag = i.box_apply_goods_d_t_o_s && i.box_apply_goods_d_t_o_s.length
          const goods = flag ? i.box_apply_goods_d_t_o_s[0] : {}
          const stock = goods.stock_number || 0
          const num = goods.goods_number || 0
          const stock_number_to_add = (num - stock) > 0 ? (num - stock) : 0
          return {
            ...i,
            stock_number_to_add
          }
        })
        this.list = this.list.concat(list)
        this.listState.more = list.length === listQuery.page_size
      }
      setTimeout(() => {
        this.listState.loading = false
        uni.stopPullDownRefresh()
      }, 500)
      this.pageLoaded = true
    },
    keyChange(value) {
      this.listQuery.mobile = value
    },
    keyClear() {
      this.listQuery.mobile = ''
    },
    search() {
      this.listQuery.page_no = 1
      this.fetchData()
    },
    updateList() {
      this.listQuery.page_no = this.curent_page_no
      this.fetchData(false, {
        ...this.listQuery,
        page_no: 1,
        page_size: this.listQuery.page_no * this.listQuery.page_size
      })
    },
    inputChange(e) {
      if (e.detail && e.detail.value !== '') {
        this.handleObj.rejectReason = e.detail.value
        this.handleObj.leastNum = (10 - e.detail.value.length)
      } else {
        this.handleObj.leastNum = 10
      }
    },
    toDetail(index) {
      const item = this.list[index]
      this.current_page_no = Math.floor(index / this.listQuery.page_size) + 1
      this.$navigateTo(`/pagesBox/approval/detail?id=${item.id}&type=approval`)
    },
    async btnClick(type, index) {
      // type 1:补库存， 2:通过，3:驳回
      const item = this.list[index]
      if (type === 1) {
        const params = {}
        const settleData = {
          shopping_list: JSON.stringify([{
            num: item.stock_number_to_add,
            goods_id: item.box_apply_goods_d_t_o_s[0].goods_id,
            sku_code: item.box_apply_goods_d_t_o_s[0].goods_sku,
            goods_type: 1,
            from_type: 11
          }]),
          new_box_order_type: 1,
          stock_goods_id: item.box_apply_goods_d_t_o_s[0].goods_id,
          stock_sku_code: item.box_apply_goods_d_t_o_s[0].goods_sku,
          is_used_coupon: 0
        }
        if (this.createOrderPermission) {
          params.boxType = 'buy'
        } else {
          params.boxType = 'apply'
          this.$store.dispatch('setGoodsTemp', {
            shopping_list: settleData.shopping_list,
            data: {
              coupon_list: [],
              hongbao_list: [],
              unusable_coupon_list: [],
              shopping_items: {
                activity_item_list: [],
                item_list: [
                  {
                    goods_id: item.box_apply_goods_d_t_o_s[0].goods_id,
                    title: item.box_apply_goods_d_t_o_s[0].goods_name,
                    num: item.stock_number_to_add,
                    vip_price: item.box_apply_goods_d_t_o_s[0].goods_price,
                    sku_code: item.box_apply_goods_d_t_o_s[0].goods_sku,
                    pic: item.box_apply_goods_d_t_o_s[0].image,
                    stock_number: item.box_apply_goods_d_t_o_s[0].stock_number,
                    need_change_num: true
                  }
                ]
              }
            },
            settleData
          })
          this.$navigateTo(formatUrlParam('/pagesBox/pick-up/index', {
            boxType: 'apply'
          }))
          return
        }
        const resSettle = await this.$api.orderApi.orderSettle(settleData)
        if (resSettle.success) {
          this.$store.dispatch('setGoodsTemp', {
            shopping_list: settleData.shopping_list,
            data: resSettle.data,
            settleData
          })
          this.$navigateTo(formatUrlParam('/pagesBox/pick-up/index', params))
        }
      } else {
        this.current_page_no = Math.floor(index / this.listQuery.page_size) + 1
        this.handleObj = {
          id: item.id,
          approvalStatus: type, // 审批状态：2-审批通过，3-审批驳回
          rejectType: 1,
          rejectReason: '',
          leastNum: 10
        }
        const title = ['', '', '温馨提示', '驳回确认'][type]
        const cancleTxt = ['', '', '我再想想', '取消'][type]
        const yesTxt = ['', '', '我确定', '提交'][type]
        const duration = type === 2 ? 5000 : 0
        this.$refs.confirm.show({
          title,
          cancleTxt,
          yesTxt,
          duration,
          maskClickClose: false,
          yesCb: async() => {
            const postData = { ...this.handleObj }
            if (postData.approvalStatus === 3 && postData.rejectType === 1) {
              postData.rejectReason = '未收到货款'
            }
            const res = await this.$api.boxApi.operateApproval(postData)
            if (res.success) {
              uni.showToast({ title: '操作成功', icon: 'none' })
              this.updateList()
            }
          }
        })
      }
    }
  }
}
</script>
